<?php

use module\home\model\User;
require_once MODEL_DIR . '/User.php';

define('AUTH_USER', 'AUTH_USER');

/**
 * class responsible for authenticating user login with given credential
 *
 * used by User controller to login
 * @package yasns
 * @subpackage library
 */
class Auth
{
	/**
	 * will perform user validation from database 
	 * if sucess will store in the session and returns true
	 * 
	 * @param string $identity
	 * @param string $credential
	 * @return boolean 
	 */
	public static function authenticate($identity, $credential)
	{
		$user = User::findByUsernameAndPassword($identity, $credential);
		if($user) {
			// serialize and store in session
			$userdata = serialize($user);
			$_SESSION[AUTH_USER] = $userdata;
			
			// and return true;
			return true;
		} else {
			// remove if any existing session
			unset($_SESSION[AUTH_USER]);
			
			// return false;
			return false;
		}
	}
	
	/**
	 * checks if user exists in the session 
	 * 
	 * @return boolean
	 */
	public static function hasIdentity()
	{
		if (!isset($_SESSION[AUTH_USER])) return false;
		
		return true;
	}
	
	/**
	 * get the stored user data from the session
	 * returns unserialized object 
	 * 
	 * @return object|null
	 */
	public static function getIdentity()
	{
		$user = (Auth::hasIdentity()) ? unserialize($_SESSION[AUTH_USER]) : null;
		
		return $user;
	}
	
	
	/**
	 * logs out user
	 * simply remove user information from current session 
	 * @return void
	 */
	public static function removeIdentity()
	{
		unset($_SESSION[AUTH_USER]);
	}
}
?>
